// ==UserScript==
// @name         下载音频和lrc，由于跨域原因，下载失败，请手动下载
// @namespace    http://kind.cn
// @version      0.1
// @description  ''
// @author       SUNSHINE
// @match        http://www.kekenet.com/cet4/*
// @grant        none
// ==/UserScript==


(function() {
    'use strict';

	init();
	var articleName123123 = '';
	function init(){
		let sample = document.querySelector('.e_title');
		let inDom = document.createElement('button');
		inDom.id = 'downloadLrc';
		inDom.setAttribute('href', 'javascript:void(0)');
		inDom.innerText = '下载文件';
		inDom.style.marginLeft = '50px';
		inDom.onclick = function() {
			articleName123123 = document.getElementById('nrtitle').innerText.replace(' ','')
			copyText(articleName123123)
			downMp3(articleName123123+".mp3")
			downLrc(articleName123123+".lrc")
		};
		sample.prepend(inDom);
	}
	function downMp3(fileName){
		var audioEl = document.getElementById('myaudio');
		if(!audioEl){
			return;
		}
		downFile(audioEl.attributes.src.nodeValue,fileName)
	}
	// 秒  转为 00:0.12,
  function secondToTime(second){
		var res = formatTwo((second%60).toFixed(2))+'';
		var munite = (second-(second%60))/60;
		res = formatTwo(munite) + ":"+res;
	    return res;
  }
  function formatTwo(num){
	for(let i=(parseInt(num) +'').length;i<2;i++){
			num = '0'+num;
	}
	return num;
  }

	function downLrc(fileName){
		if (typeof lrc_arr == "undefined") {
			return;
		}
		var text= '';
		console.log(lrc_arr)
		for(let item of lrc_arr){
			text += "["+secondToTime(item["start"])+"]"+item["en"] +"\n"+item["cn"]+"\n"
		}
		downText(text.substring(0,text.length-1),fileName)
	}
	function downFile(url,filename){
		var a = document.createElement('a');
		a.href = url;
		a.download = filename;
		document.body.appendChild(a);
		a.click();
		window.URL.revokeObjectURL(url);
		//移除元素
		document.body.removeChild(a);

	}
	function downText(connet,name){
		//保存本次标记结果并清空
						//创建元素
						var ele = document.createElement('a');
						//设置下载文件名
						ele.download = name;
						//隐藏元素
						ele.style.display = "none";
						//字符内容转变成blob地址
						var blob = new Blob([connet]);
						//如果是链接，这里也可以直接设置链接地址
						ele.href = URL.createObjectURL(blob);
						document.body.appendChild(ele);
						//模拟点击
						ele.click();
						//移除元素
						document.body.removeChild(ele);
	}

	        function copyText(text) {
	            const input = document.createElement('input');
    document.body.appendChild(input);
    input.setAttribute('value', text);
    input.select();
    if (document.execCommand('copy')) {
        document.execCommand('copy');
        console.log('复制成功');
    }
 document.body.removeChild(input);
	        }

})();